capture log close
log using $log/AED_dataprep_04_outcome_reg_weekly, text replace
   
clear
set mem 6000m
set matsize 800
set more off

set trace off
   
/* ----------------------------------------------- */
/* --- Generating regional outcome variables ----- */
/* ----------------------------------------------- */


local iebversion v901  


/*We start with the calender months Jan - Mar. This is necessary to prevent STATA to collapse*/
forvalues year =1999/2010  {
		
		use $orig/AED_9310_v1, clear
		
		rename persnr iza_id
		rename begorig beg_orig
		rename endorig end_orig
		
		
		
		qui drop if end_orig<mdy(1,1,`year')
		qui drop if beg_orig>mdy(12,31,`year')
		gen jahr=`year'
		
		joinby betnr jahr using $orig/AED_9310_v1_bhp_basis_v1, unmatched(master)
		tab _merge
		drop _merge
		
		
		keep iza_id beg_orig end_orig wo_kreis wo_aa ao_aa traeger
		sort iza_id beg_orig
		
	
		foreach month in 01 02 03 04 05 06 07 08 09 10 11 12 {
		
		  forvalue week = 1/4 {
	
			di "### `year' `month' `week'"
			di c(current_time)
			if "`month'"=="01" { 
				local m "Jan"
			}	
			if "`month'"=="02" { 
				local m "Feb"
			}	
			if "`month'"=="03" { 
				local m "Mar"
			}	
			if "`month'"=="04" { 
				local m "Apr"
			}	
			if "`month'"=="05" { 
				local m "May"
			}	
			if "`month'"=="06" { 
				local m "Jun"
			}	
			if "`month'"=="07" { 
				local m "Jul"
			}	
			if "`month'"=="08" { 
				local m "Aug"
			}	
			if "`month'"=="09" { 
				local m "Sep"
			}	
			if "`month'"=="10" { 
				local m "Oct"
			}	
			if "`month'"=="11" { 
				local m "Nov"
			}
			if "`month'"=="12" { 
				local m "Dec"
			}

			
			if `week' == 1 {
				local d 5
			}
			if `week' == 2 {
				local d 12
			}
			if `week' == 3 {
				local d 19
			}
			if `week' == 4 {
				local d 26
			}
			
								
			/*Information regarding place of residence and working location*/
			foreach reg in wo_kreis wo_aa ao_aa traeger {
				
				#delimit ;
				qui by iza_id: gen iza_`reg'_`year'`month'`week'_0 = `reg'  if (beg_orig<=d(`d'`m'`year')
				& end_orig>=d(`d'`m'`year'));
				#delimit cr
				
				
				qui tostring iza_`reg'_`year'`month'`week'_0, replace
				qui by iza_id: gen     iza_`reg'_`year'`month'`week'_temp = iza_`reg'_`year'`month'`week'_0
				qui by iza_id: replace iza_`reg'_`year'`month'`week'_temp = iza_`reg'_`year'`month'`week'_temp[_n-1] if iza_`reg'_`year'`month'`week'_0=="" | iza_`reg'_`year'`month'`week'_0=="."
				qui by iza_id: gen     iza_`reg'_`year'`month'`week'      = iza_`reg'_`year'`month'`week'_temp[_N]
				drop iza_`reg'_`year'`month'`week'_temp iza_`reg'_`year'`month'`week'_0			
				
			}/*end:reg*/
			}/*end:week*/
			} /* End: m (month) */
			
	qui bys iza_id: drop if _n>1
	/* Reduce Data */
	
	keep iza*
	sort iza_id
	
	compress
	save $data/outcome_reg_weekly_y`year'_`iebversion', replace
	
	
} /* End: year */
	
	
log close		

	
